package com.k.kpp.util.rpc.netty.udp.client;

import com.k.kpp.util.rpc.netty.XMLUtils;
import com.k.kpp.util.rpc.netty.model.XmlResult;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import javax.xml.bind.JAXBException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author k
 */
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private Map<String,Object> retMap ;
    public UdpClientHandler(Map<String,Object> resultMap){
        retMap = resultMap;

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        String receiveXml = packet.content().toString(StandardCharsets.UTF_8);
        System.out.println("udp client receive0：" + receiveXml);
        try {
            XmlResult result = XMLUtils.xmlToObj(XmlResult.class,receiveXml,"utf-8");
            System.out.println("udp client receive0:cov:"+result);
            retMap.put(result.getGuid(),result);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 向对方端发送消息
//        ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
//        ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
    }

}
